from network import QKDNetwork
from generate import GenerateNetwork
from rounding import solver
from log import clearContent, addContent

def runGenerateCluster(clusterID, numNodes):
    path = f"../template/capacity_{clusterID*10}_cluster.txt"
    clearContent(path)
    alpha_start = 1.25
    alpha_decrease = 0.035
    alpha = alpha_start - numNodes * alpha_decrease
    beta = 0.1
    GenerateNetwork.generate_network_with_var_capacity(numNodes, alpha, beta, clusterID) # 生成一个网络
    net = QKDNetwork("generate.txt")
    x_ret, p_ret, alpha_ret = solver(net, len(net.nodeList), {'alpha': alpha, 'beta': beta, 'seed': 1})
    addContent(path, f"{numNodes}")                         # 节点数
    addContent(path, f"{alpha} {beta}")                     # Aplha-Beta-Seed
    addContent(path, f"{len(net.linkListCapacity)}")        # 边数量
    for item in net.linkListCapacity:
        if(item.startNode < item.endNode):
            addContent(path, f"{item.startNode} {item.endNode} {item.capacity}")
    
    r = range(1, numNodes + 1)
    for m in r:
        for n in r:
            path_length = 0
            path_nodes = []
            for i in r:
                for j in r:
                    if(x_ret[m][n][i][j] != 0):
                        path_length += x_ret[m][n][i][j]
                        path_nodes.append([i, j])
            if(path_length != 0):
                addContent(path, f"{int(path_length)} {m} {n}")
                # print(path_nodes)
                for path_link in path_nodes:
                    # path_link [起点, 终点]
                    i_tmp = path_link[0]
                    j_tmp = path_link[1]
                    str_tmp = f"{i_tmp} {j_tmp} "
                    for link in net.linkListCapacity:
                        ratio = p_ret[m][n][i_tmp][j_tmp][link.startNode][link.endNode]
                        if(ratio != 0):
                            str_tmp += f"{link.startNode} {link.endNode} {ratio} "
                        ratio = p_ret[m][n][i_tmp][j_tmp][link.endNode][link.startNode]
                        if(ratio != 0):
                            str_tmp += f"{link.endNode} {link.startNode} {ratio} "
                    str_tmp = str_tmp[:-1]
                    addContent(path, str_tmp)
                
    # print(x_ret)
    # print(p_ret)
    # print(alpha_ret)

for i in range(1, 10):
    clearContent("log.txt")
    runGenerateCluster(i, 8)